import Taro from "@tarojs/taro";
import { HTTP_STATUS } from "../constants/status";
import { logError } from "./index";

// const baseUrl = "https://music.lsqy.tech/api";
const baseUrl = "https://web.codercheng.top";

export default function request(
  url,
  data,
  method = "GET",
  contentType = "application/json"
) {
  return new Promise((reslove, reject) => {
    Taro.request({
      url: url.indexOf("http") !== -1 ? url : baseUrl + url,
      data,
      method,
      header: {
        "content-type": contentType,
        cookie: Taro.getStorageSync("cookies")
      },
      success: res => {
        setCookie(res);
        if (res.statusCode === HTTP_STATUS.SUCCESS) {
          reslove(res.data);
        } else {
          if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
            reject(res);
            return logError("api", "请求资源不存在");
          } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
            reject(res);
            return logError("api", "服务端出现了问题");
          } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
            reject(res);
            return logError("api", "没有权限访问");
          } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
            Taro.clearStorage();
            Taro.navigateTo({
              url: "/pages/login/index"
            });
            return logError("api", "请先登录");
          }
          return logError(
            "api",
            "请求接口出现问题",
            "请求异常,网络繁忙或api异常"
          );
        }
      },
      fail: err => {
        logError("api", "请求接口出现问题", "请求异常,网络繁忙或api异常");
        return reject(err);
      }
    });
  });
}
["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
  method => {
    request[method] = ({ url, data, contentType = "" }) =>
      request(url, data, method, contentType);
  }
);

const setCookie = res => {
  if (res.cookies && res.cookies.length > 0) {
    let cookies = "";
    res.cookies.forEach((cookie, index) => {
      // windows的微信开发者工具返回的是cookie格式是有name和value的,在mac上是只是字符串的
      if (cookie.name && cookie.value) {
        cookies +=
          index === res.cookies.length - 1
            ? `${cookie.name}=${cookie.value};expires=${cookie.expires};path=${cookie.path}`
            : `${cookie.name}=${cookie.value};`;
      } else {
        cookies += `${cookie};`;
      }
    });
    Taro.setStorageSync("cookies", cookies);
  }
  if (res.header && res.header["Set-Cookie"]) {
    Taro.setStorageSync("cookies", res.header["Set-Cookie"]);
  }
};
